package com.skyc.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.skyc.entity.Shop;
import com.skyc.entity.User;
import com.skyc.service.ShopService;
import com.skyc.service.UserService;
import com.skyc.service.impl.ShopServicImpl;

/**
 * Servlet implementation class AServlet
 */
@WebServlet("/ShopCartServlet")
public class ShopCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	UserService us = null;
	PrintWriter out = null;
	HttpSession session = null;
	ShopService ss = null;
	User user = null;
	Gson gson = null;

	protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
		doPost(req, response);

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// request.setCharacterEncoding("utf-8");
		// response.setContentType("text/html;charset=utf-8");
		// response.setCharacterEncoding("utf-8");
		session = request.getSession();
		// ServletContext application=getServletContext();
		String flag = request.getParameter("flag");// 来源
		out = response.getWriter();
		ss = new ShopServicImpl();
		user = (User) session.getAttribute("user");
		gson = new Gson();
		if (session.getAttribute("sum") == null) {
			session.setAttribute("sum", 0);
		}

		if (user == null) {
			session.removeAttribute("sum");
			session.removeAttribute("shopnum");
			session.removeAttribute("shops");
		}
		if (flag != null && user != null) {
			switch (flag) {
			case "fush":// 刷新
				doFush(request, response);
				break;
			case "query":// 进界面前默认刷新
				doQuery(request, response);
				break;
			case "index":// 从其他界面进来
				doIndex(request, response);
				break;
			case "sum":// 单个商品总价前
				doSum(request, response);
				break;
			case "delete":// 删除商品
				doDeleteShop(request, response);
				break;
			case "pricessum":// 所有商品总价
				doPricessum(request, response);
				break;
			case "sumall":
				doSumall(request, response);
				break;
			case "deleteall":// 删除选中的商品
				doDeleteAll(request, response);
				break;
			case "addshop":// 添加到购物车
				doAddShop(request, response);
				break;
			case "shopsum":// 购物车总共有几个商品
				doShopSum(request, response);
				break;
			default:
				break;
			}
			session.setAttribute("shopnum", ss.returnCountByUID(user.getUid() + ""));
		} else {
			out.print("<script>location='shopcart.jsp';</script>");
		}

		out.flush();
		out.close();
	}

	private void doShopSum(HttpServletRequest request, HttpServletResponse response) {
		String sid = request.getParameter("sid");
		String val = request.getParameter("val");
		Shop shop = ss.queryBySID(sid);
		int value = -1;
		try {
			value = Integer.valueOf(val);
		} catch (Exception e) {
			e.printStackTrace();
			out.print("x");
			return;
		}
		int snum = shop.getSnum();
		if (snum != value) {
			if (ss.updateBySID(sid + "", val)) {
				out.print(value - snum);
			}else {
				out.print("y");
			}

		} else {
			out.print("y");
		}

	}

	private void doFush(HttpServletRequest request, HttpServletResponse response) {
		List<Shop> shops = ss.queryByUID(user.getUid() + "");
		session.setAttribute("shopnum", ss.returnCountByUID(user.getUid() + ""));
		session.setAttribute("shops", shops);
		String[] shop_img = new String[shops.size()];
		setImgUtil(shops, shop_img);
		String str1 = "";
		str1 = gson.toJson(shops);

		out.print(str1);

	}

	private void doQuery(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		session.setAttribute("shopnum", ss.returnCountByUID(user.getUid() + ""));
		List<Shop> shops = ss.queryByUID(user.getUid() + "");
		session.setAttribute("shops", shops);
		String[] shop_img = new String[shops.size()];
		setImgUtil(shops, shop_img);
		request.getRequestDispatcher("shopcart_show.jsp").forward(request, response);

	}

	private void doAddShop(HttpServletRequest request, HttpServletResponse response) {
		String cid = request.getParameter("cid");
		String snum1 = request.getParameter("snum");
		int num = 0;
		int snum = 0;
		if (snum1 == null || "".equals(snum1)) {
			snum = 1;
		} else {
			try {
				snum = Integer.valueOf(snum1);
			} catch (Exception e) {
				e.printStackTrace();
				num = ss.returnCountByUID(user.getUid() + "");
				session.setAttribute("shopnum", num);
				out.print(num);
				return;
			}

		}
		Shop shop = ss.queryByCIDUID(cid,user.getUid()+"");
		if (shop != null) {
			snum += shop.getSnum();
			ss.updateBySID(shop.getSid() + "", snum + "");
			num = ss.returnCountByUID(user.getUid() + "");
			session.setAttribute("shopnum", num);
			out.print(num);
		} else {
			ss.addShop(user.getUid() + "", cid + "", snum + "");
			num = ss.returnCountByUID(user.getUid() + "");
			session.setAttribute("shopnum", num);
			out.print(num);

		}

	}

	private void doDeleteAll(HttpServletRequest request, HttpServletResponse response) {
		String str = request.getParameter("sids");
		List<String> lists = gson.fromJson(str, new TypeToken<List<String>>() {
		}.getType());
		List<Shop> shoplist=new ArrayList<Shop>();
		for (int i = 0; i < lists.size(); i++) {
			shoplist.add(ss.queryBySID(lists.get(i)));
			ss.deleteBySID(lists.get(i));
		}
		session.setAttribute("pay_shops", shoplist);
		List<Shop> shops = ss.queryByUID(user.getUid() + "");
		session.setAttribute("shops", shops);
		String[] shop_img = new String[shops.size()];
		setImgUtil(shops, shop_img);
		out.print("1");
	}

	private void doSumall(HttpServletRequest request, HttpServletResponse response) {
		String checked = request.getParameter("clicked");
		String str = "";
		if (Boolean.valueOf(checked)) {
			List<Shop> shops = ss.queryByUID(user.getUid() + "");
			String[] shop_img = new String[shops.size()];
			setImgUtil(shops, shop_img);
			session.setAttribute("shops", shops);
			str = gson.toJson(shops);
		}
		out.print(str);

	}

	private void doPricessum(HttpServletRequest request, HttpServletResponse response) {

		String checked = request.getParameter("clicked");
		String pricessum = request.getParameter("pricessum");
		if (pricessum != null && checked != null) {
			int prices = Integer.valueOf(pricessum);
			String sum = null;
			if (session.getAttribute("sum") != null) {
				sum = session.getAttribute("sum").toString();
			}
			int a = 0;
			if (sum != null) {
				a = Integer.valueOf(sum);
			}

			if (Boolean.valueOf(checked)) {
				a = prices + a;
			} else {
				a = a - prices;
			}
			session.setAttribute("sum", a);
			out.print(a);

		}

	}

	private void doIndex(HttpServletRequest request, HttpServletResponse response) {
		session.setAttribute("shopnum", ss.returnCountByUID(user.getUid() + ""));
		List<Shop> shops = ss.queryByUID(user.getUid() + "");
		session.setAttribute("shops", shops);
		String[] shop_img = new String[shops.size()];
		setImgUtil(shops, shop_img);
		out.print("<script>location='shopcart.jsp';</script>");
	}

	private void doDeleteShop(HttpServletRequest request, HttpServletResponse response) {
		String sid = request.getParameter("sid");
		if (ss.deleteBySID(sid)) {
			List<Shop> shops = ss.queryByUID(user.getUid() + "");
			String[] shop_img = new String[shops.size()];
			setImgUtil(shops, shop_img);
			session.setAttribute("shops", shops);
			out.print("1");
		}

	}

	private void doSum(HttpServletRequest request, HttpServletResponse response) {
		String snum = request.getParameter("snum");
		String sid1 = request.getParameter("sid");
		String ische = request.getParameter("checkedis");
		if (snum != null && sid1 != null) {
			if (ss.updateBySID(sid1, snum)) {
				List<Shop> shops = ss.queryByUID(user.getUid() + "");
				String[] shop_img = new String[shops.size()];
				setImgUtil(shops, shop_img);
				session.setAttribute("shops", shops);
				int price = Integer.valueOf(request.getParameter("price"));
				int sum = Integer.valueOf(session.getAttribute("sum").toString());
				if (Boolean.valueOf(ische)) {
					String val = request.getParameter("val");
					if ("+".equals(val)) {
						session.setAttribute("sum", sum + price);
						out.print("1");
					}
					if ("-".equals(val)) {
						session.setAttribute("sum", sum - price);
						out.print("1");
					}
					if (!"+".equals(val) && !"-".equals(val)) {
						try {
							session.setAttribute("sum", sum - price * Integer.valueOf(val));
						} catch (Exception e) {
							e.printStackTrace();
							out.print(0);
						}

					}

				}
			}

		}
	}

	private void setImgUtil(List<Shop> shops, String[] shop_img) {
		if (shops != null) {// 图片
			// String[] shop_img = new String[shops.size()];
			for (int i = 0; i < shops.size(); i++) {
				String[] cc = shops.get(i).getClothes().getCimgurl().split("/");
				if (cc != null || cc.length != 0) {
					shop_img[i] = cc[1];// 用分号切割取第二张图
				}
			}

			session.setAttribute("shop_img", shop_img);
		}
	}
}
